import { View } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';

import { NoticeResponseItem } from '../../types/service';

import './NoticeMessage.scss';

interface NoticeMessage {
  messages: NoticeResponseItem[];
  displayTime?: number; // 消息在喇叭处停留的时间
  slideSpeed?: number;  // 滑动动画的速度
}

const NoticeMessage: React.FC<NoticeMessage> = ({
  messages,
  displayTime = 3000,  // 默认停留2秒
  slideSpeed = 3000    // 默认滑动1秒
}) => {
  const indexRef = useRef(0);
  const [currentMessage, setCurrentMessage] = useState<NoticeResponseItem>({} as NoticeResponseItem);
  const [isSlidingIn, setIsSlidingIn] = useState(true);
  const animationTimerRef = useRef<NodeJS.Timeout | null>(null);
  const messageList = useRef<NoticeResponseItem[]>([]);

  // 初始化消息列表 
  useEffect(() => {
    if (Array.isArray(messages)) {
      messageList.current = messages;
    } else {
      messageList.current = [messages || {}];
    }
  }, [messages]);

  // 处理消息切换
  const switchMessage = () => {
    if (messageList.current.length === 0) {
      return;
    }

    // 清除之前的定时器
    if (animationTimerRef.current) {
      clearTimeout(animationTimerRef.current);
    }

    // 设置当前消息
    setCurrentMessage(messageList.current[indexRef.current]);
    setIsSlidingIn(true);
    
    // 动画结束后保持显示
    animationTimerRef.current = setTimeout(() => {
      setIsSlidingIn(false);
    }, slideSpeed);

    // 准备下一条消息
    const nextIndex = (indexRef.current + 1) % messageList.current.length;
    
    // 在显示时间结束后切换到下一条消息
    animationTimerRef.current = setTimeout(() => {
      indexRef.current = nextIndex;
      switchMessage();
    }, slideSpeed + displayTime);
  };

  useEffect(() => {
    // 启动第一条消息
    if (messageList.current.length > 0) {
      switchMessage();
    }

    return () => {
      if (animationTimerRef.current) {
        clearTimeout(animationTimerRef.current);
      }
    };
  }, [messageList.current, displayTime, slideSpeed]);

  return (
    <View className='notice-container'>
      <MaterialIcons name="volume-up" color="#ffc107" size={25} />
      <View className='notice-wrapper'>
        <View 
          className='notice-text'
          style={{
            animation: isSlidingIn 
              ? `slideFromRight ${slideSpeed}ms ease-out forwards` 
              : 'none',
            animationFillMode: 'forwards'
          }}
        >

          {currentMessage?.type === 1 ? (
            <View className='notice-system-message'>
              {currentMessage?.content || ''}
            </View>
          ) : (
            <View className='notice-content'>
              {currentMessage?.content || ''}
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

export default NoticeMessage;